/*
 * @Author: pardon110
 * @Date: 2024-03-18 09:05:49
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-18 11:13:49
 * @FilePath: \days7\web\middleware\main.go
 * @Description:
 */
package main

import (
	"log"
	"net/http"
	"time"

	"days7.test/web/middleware/mid"
)

func main() {
	r := mid.New()
	r.Use(mid.Logger())

	r.GET("/", func(c *mid.Context) {
		c.HTML(http.StatusOK, "<h1>Hello pardon110</h1>")
	})

	v2 := r.Group("/v2")
	v2.Use(onlyForV2()) // v2 group middleware
	{
		v2.GET("/hello/:name", func(c *mid.Context) {
			// expect /hello/pardon110
			c.String(http.StatusOK, "hello %s, you're at %s\n", c.Param("name"), c.Path)
		})
	}

	r.Run(":8080")
}

func onlyForV2() mid.HandlerFunc {
	return func(c *mid.Context) {
		// Start timer
		t := time.Now()
		// if a server error occurred
		c.Fail(500, "Internal Server Error")
		// Calculate resolution time
		log.Printf("[%d] %s in %v for group v2", c.StatusCode, c.Req.RequestURI, time.Since(t))
	}
}
